<template>
  <div class="login-container">
    <!-- 语言切换组件 -->
    <LanguageSwitcher @language-change="handleLanguageChange" />

      <div class="box-container">
      <div class="login-banner">
        <img src="@/assets/images/image-banner.png" alt="仓库管理系统插图">
      </div>
   
      <div class="login-form-container" style="flex: 1;" >
        <div class="login-form-header">
          <img src="@/assets/images/banner-log.png" alt="">
        </div>
        
        <div class="login-form-tabs">
          <!-- <div 
            :class="['tab-item', activeTab === 'password' ? 'active' : '']" 
            @click="activeTab = 'password'"
          >
            密码登录
          </div> -->
          <!-- <div 
            :class="['tab-item', activeTab === 'captcha' ? 'active' : '']" 
            @click="activeTab = 'captcha'"
          >
            验证码登录
          </div> -->
        </div>
        
        <el-form 
          ref="loginFormRef" 
          :model="loginForm" 
          :rules="loginRules"
          class="login-form"
        >
          <!-- 邮箱输入框 -->
          <el-form-item prop="email" style="margin-top: 80px;">
            <el-input 
              v-model="loginForm.email" 
              :placeholder="t('emailPlaceholder')" 
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 密码输入框 - 密码登录模式 -->
          <el-form-item v-if="activeTab === 'password'" prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              :placeholder="t('passwordPlaceholder')" 
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 图形验证码 - 密码登录模式 -->
          <!-- <el-form-item v-if="activeTab === 'password'" prop="imageCaptcha">
            <div class="captcha-container">
              <el-input 
                v-model="loginForm.imageCaptcha" 
                placeholder="请输入右侧验证码" 
              />
              <div class="image-captcha" @click="refreshImageCaptcha">
                {{ imageCaptcha }}
              </div>
            </div>
          </el-form-item> -->
          
          <!-- 验证码输入框 - 验证码登录模式 -->
          <!-- <el-form-item v-if="activeTab === 'captcha'" prop="captcha">
            <div class="captcha-container">
              <el-input 
                v-model="loginForm.captcha" 
                placeholder="请输入验证码" 
              />
              <el-button type="primary" :disabled="isCaptchaLoading" @click="handleSendCaptcha">
                {{ captchaButtonText }}
              </el-button>
            </div>
          </el-form-item> -->
          <!-- <el-link type="primary" @click="goToForg?"otPassword" style="float: right;">忘记密码</el-link> -->
          <!-- 登录按钮 -->
          <el-button 
            type="primary" 
            class="login-button" 
            :loading="isLoading" 
            @click="handleLogin"
          >
            {{ t('loginButton') }}
          </el-button>
          
          <!-- 测试连接按钮 -->
          <!-- <el-button 
            type="info" 
            class="test-connection-button" 
            :loading="isTestingConnection" 
            @click="testConnection"
          >
            测试服务器连接
          </el-button>
		   -->
		  <!-- 记住密码和忘记密码 -->
		  <!-- <div class="login-options">
		    <el-checkbox v-model="rememberPassword">30天免登录</el-checkbox>
			<el-checkbox v-model="rememberUsername">记住密码</el-checkbox>
		  
		  </div> -->
   
        </el-form>
      </div>
    </div>
 
   
    
    <!-- <div class="login-footer">
      <span>如遇问题，联系客服热线</span>
      <span class="login-footer-phone">	400-6529088</span>
    </div> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Back, Check } from '@element-plus/icons-vue'
import LanguageSwitcher from '@/components/common/LanguageSwitcher.vue'
import { login } from '@/api/modules/user'


const router = useRouter()

// 登录表单相关
const loginFormRef = ref(null)
const activeTab = ref('password')
const rememberPassword = ref(false)
const rememberUsername = ref(false)
const isLoading = ref(false)
const isCaptchaLoading = ref(false)
const isTestingConnection = ref(false)
const captchaButtonText = ref('发送验证码')
const imageCaptcha = ref('36+22')

// 当前语言状态
const currentLanguage = ref('zh-CN')

// 多语言文本配置
const i18nTexts = ref({
  'zh-CN': {
    emailPlaceholder: '请输入邮箱地址',
    passwordPlaceholder: '请输入密码',
    loginButton: '登录',
    emailRequired: '请输入邮箱地址',
    emailFormat: '请输入正确的邮箱格式',
    passwordRequired: '请输入密码',
    passwordMinLength: '密码长度不能少于6位',
    captchaRequired: '请输入验证码',
    captchaFormat: '验证码为6位数字',
    imageCaptchaRequired: '请输入图形验证码',
    captchaButton: '发送验证码',
    captchaSending: '发送中...',
    captchaSent: '验证码已发送至',
    captchaCountdown: 's',
    loginSuccess: '登录成功',
    loginError: '邮箱或密码错误',
    warehouseRequired: '请选择仓库',
    warehouseSuccess: '仓库选择成功',
    languageSwitched: '语言已切换到'
  },
  'en-US': {
    emailPlaceholder: 'Please enter email address',
    passwordPlaceholder: 'Please enter password',
    loginButton: 'Login',
    emailRequired: 'Please enter email address',
    emailFormat: 'Please enter a valid email format',
    passwordRequired: 'Please enter password',
    passwordMinLength: 'Password must be at least 6 characters',
    captchaRequired: 'Please enter verification code',
    captchaFormat: 'Verification code must be 6 digits',
    imageCaptchaRequired: 'Please enter image verification code',
    captchaButton: 'Send Code',
    captchaSending: 'Sending...',
    captchaSent: 'Verification code sent to',
    captchaCountdown: 's',
    loginSuccess: 'Login successful',
    loginError: 'Invalid email or password',
    warehouseRequired: 'Please select warehouse',
    warehouseSuccess: 'Warehouse selected successfully',
    languageSwitched: 'Language switched to'
  }
})

// 获取当前语言的文本
const t = (key) => {
  return i18nTexts.value[currentLanguage.value][key] || key
}

// 登录表单数据
const loginForm = reactive({
  email: '',      // 使用email字段匹配API要求
  password: '',
  captcha: '',
  imageCaptcha: ''
})

// 选择仓库相关
const showWarehouseSelect = ref(false)
const selectedWarehouse = ref('')
const warehouseList = ref([
  { id: '1', name: '华东上海仓' },
  { id: '2', name: '华东苏州仓' },
  { id: '3', name: '华东杭州仓' },
  { id: '4', name: '华东厦门仓' },
  { id: '5', name: '华东南京仓' },
])

// 表单验证规则 - 使用计算属性支持多语言
const loginRules = computed(() => ({
  // email: [
  //   { required: true, message: t('emailRequired'), trigger: 'blur' },
  //   { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: t('emailFormat'), trigger: 'blur' }
  // ],
  // password: [
  //   { required: true, message: t('passwordRequired'), trigger: 'blur' },
  //   { min: 6, message: t('passwordMinLength'), trigger: 'blur' }
  // ],
  captcha: [
    { required: true, message: t('captchaRequired'), trigger: 'blur' },
    { pattern: /^\d{6}$/, message: t('captchaFormat'), trigger: 'blur' }
  ],
  imageCaptcha: [
    { required: true, message: t('imageCaptchaRequired'), trigger: 'blur' }
  ]
}))

// 刷新图形验证码
const refreshImageCaptcha = () => {
  // 生成简单的计算题
  const num1 = Math.floor(Math.random() * 50) + 10
  const num2 = Math.floor(Math.random() * 20) + 10
  imageCaptcha.value = `${num1}+${num2}`
}

// 发送短信验证码
const handleSendCaptcha = () => {
  if (!loginForm.email) {
    ElMessage.warning(t('emailRequired'))
    return
  }
  
  // 校验邮箱格式
  // if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(loginForm.email)) {
  //   ElMessage.warning(t('emailFormat'))
  //   return
  // }
  
  isCaptchaLoading.value = true
  captchaButtonText.value = t('captchaSending')
  
  // 模拟发送验证码请求
  setTimeout(() => {
    ElMessage.success(`${t('captchaSent')} ${loginForm.email}`)
    isCaptchaLoading.value = false
    
    // 倒计时
    let count = 60
    captchaButtonText.value = `${count}${t('captchaCountdown')}`
    const timer = setInterval(() => {
      count--
      captchaButtonText.value = `${count}${t('captchaCountdown')}`
      if (count <= 0) {
        clearInterval(timer)
        captchaButtonText.value = t('captchaButton')
        isCaptchaLoading.value = false
      }
    }, 1000)
  }, 1500)
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  loginFormRef.value.validate(async (valid) => {
    if (!valid) return

    isLoading.value = true

    try {
      // 调用登录API
      const response = await login({
        email: loginForm.email,
        password: loginForm.password
      })
      console.log(response,'response===============')
      // 根据图片中的API响应格式处理
      if (response.access_token) {
        // 存储access_token到localStorage
        localStorage.setItem('access_token', response.access_token)
        
        // 显示登录成功消息
        ElMessage.success(t('loginSuccess'))
        
        // 跳转到主页面
        router.push('/dashboard')
      } else {
        // 如果响应格式不符合预期
        ElMessage.error(t('loginError'))
      }
    } catch (error) {
      // 接口调用失败，提供更详细的错误信息
      console.error('登录失败:', error)
      
      // 根据不同的错误类型显示不同的提示
      if (error.response) {
        // 服务器响应了错误状态码
        ElMessage.error(error.response.data)
    
      } else {
       
        // 其他错误
        ElMessage.error(error.data.detail)
      }
    } finally {
      isLoading.value = false
    }
  })
}

// 测试服务器连接
const testConnection = async () => {
  isTestingConnection.value = true
  
  try {
    // 尝试访问后端服务器的根路径
    const response = await fetch('http://149.88.80.204:8000/', {
      method: 'GET',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      ElMessage.success('服务器连接正常！')
    } else {
      ElMessage.warning(`服务器响应异常 (${response.status})`)
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('无法连接到服务器，请检查网络或联系管理员')
  } finally {
    isTestingConnection.value = false
  }
}

// 前往忘记密码页面
const goToForgotPassword = () => {
  console.log('正在跳转到忘记密码页面...');
  router.push({ path: '/forgot-password' });
}

// 返回登录页面
const backToLogin = () => {
  showWarehouseSelect.value = false
  selectedWarehouse.value = ''
}

// 选择仓库
const selectWarehouse = (warehouse) => {
  selectedWarehouse.value = warehouse.id
}

// 确认选择仓库
const confirmWarehouse = () => {
  if (!selectedWarehouse.value) {
    ElMessage.warning(t('warehouseRequired'))
    return
  }
  
  // 保存选择的仓库信息
  const selected = warehouseList.value.find(item => item.id === selectedWarehouse.value)
  localStorage.setItem('selectedWarehouse', JSON.stringify(selected))
  
  ElMessage.success(t('warehouseSuccess'))

}

// 处理语言切换
const handleLanguageChange = (language) => {
  console.log('语言已切换到:', language.label)
  // 更新当前语言状态
  currentLanguage.value = language.value
  // 更新验证码按钮文本
  captchaButtonText.value = t('captchaButton')
  // 显示切换成功提示
  // ElMessage.success(`${t('languageSwitched')} ${language.label}`)
}

// 检查是否有记住登录信息
onMounted(() => {
  const rememberLogin = localStorage.getItem('rememberLogin')
  if (rememberLogin) {
    try {
      const data = JSON.parse(rememberLogin)
      if (data.expires > Date.now()) {
        // 未过期，自动填充邮箱
        loginForm.email = data.email
        rememberPassword.value = true
      } else {
        // 已过期，清除记住登录信息
        localStorage.removeItem('rememberLogin')
      }
    } catch (e) {
      localStorage.removeItem('rememberLogin')
    }
  }
  
  // 检查是否记住邮箱密码
  const rememberCredentials = localStorage.getItem('rememberCredentials')
  if (rememberCredentials) {
    try {
      const credentials = JSON.parse(rememberCredentials)
      loginForm.email = credentials.email
      loginForm.password = credentials.password
      rememberUsername.value = true
    } catch (e) {
      localStorage.removeItem('rememberCredentials')
    }
  }
  
  // 初始化图形验证码
  refreshImageCaptcha()
})
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  background :#2878ff url('@/assets/images/bg.png') fixed 50%;
  align-items: center;
  justify-content: center;
  background-size: cover;
  background-position: center;
}

.login-logo {
  position: absolute;
  top: 20px;
  left: 20px;
  font-size: 32px;
  font-weight: bold;
  color: #0165FF;
}

.login-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height:80%;
  width: 70%;
  padding: 0 20px;
  
 
}
.box-container{
  background-color: #ffff;
  display: flex;
  border-width: thin;
  justify-content: space-between;
  max-width: 100%;
  outline: none;
  text-decoration: none;
  transition-property: box-shadow, opacity;
  word-wrap: break-word;
  position: relative;
  white-space: normal;
  border-radius: 10px;
  width:55%;
  height: 70%;
  padding: 50px 20px 30px 50px ;
  box-sizing: border-box;
  background-color: #fff;
}
.login-banner {
  flex: 1;
 
  display: flex;
  justify-content: center;
  align-items: center;
  
  img {
    width: 100%;
    max-width: 600px;
  }
}

.login-form-container, .warehouse-select-container {
 
  // background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  // box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  // border: 1xp solid red;
}

.login-form-header {
  text-align: left;
  margin-bottom: 30px;
  // border: 1xp solid red;
 
  h2 {
    font-size: 24px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 8px;
  }
  
  h3 {
    font-size: 18px;
    font-weight: normal;
    color: #606266;
  }
}

.login-form-tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  
  .tab-item {
    padding: 0 10px 10px;
    margin-right: 20px;
    cursor: pointer;
    font-size: 16px;
    color: #606266;
    
    &.active {
      color: #0165FF;
      font-weight: 500;
      border-bottom: 2px solid #0165FF;
    }
  }
}

.login-form {
  .captcha-container {
    display: flex;
    
    .el-input {
      flex: 1;
      margin-right: 10px;
    }
    
    .el-button {
      width: 120px;
    }
    
    .image-captcha {
      width: 120px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      background: #f5f7fa;
      color: #303133;
      font-size: 20px;
      font-weight: bold;
      cursor: pointer;
      user-select: none;
      border-radius: 4px;
    }
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

.login-button, .confirm-button {
  width: 100%;
  margin-top: 20px;
  padding: 12px 0;
  font-size: 16px;
  background-color: #0165FF;
  border-color: #0165FF;
  
  &:hover, &:focus {
    background-color: #1975ff;
    border-color: #1975ff;
  }
}

.test-connection-button {
  width: 100%;
  margin-top: 10px;
  padding: 8px 0;
  font-size: 14px;
  background-color: #909399;
  border-color: #909399;
  
  &:hover, &:focus {
    background-color: #a6a9ad;
    border-color: #a6a9ad;
  }
}

.login-footer {
  text-align: center;
  padding: 20px 0;
  color: #606266;
  font-size: 16px;
  &-phone{
	  color: #0165FF;
	  font-weight:600;
  }
}

// 仓库选择样式
.warehouse-select-header {
  position: relative;
  margin-bottom: 30px;
  text-align: center;
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
  
  .back-to-login {
    position: absolute;
    left: 0;
    top: 0;
    display: flex;
    align-items: center;
    color: #0165FF;
    cursor: pointer;
    font-size: 14px;
    
    .el-icon {
      margin-right: 4px;
    }
  }
}

.warehouse-list {
  margin-top: 20px;
}

.warehouse-item {
  position: relative;
  padding: 12px 16px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  &:hover {
    border-color: #0165FF;
  }
  
  &.selected {
    border-color: #0165FF;
    color: #0165FF;
    background-color: #F0F7FF;
  }
}

// 响应式处理
@media (max-width: 1200px) {
  .login-banner {
    display: none;
  }
  
  .login-form-container, .warehouse-select-container {
    width: 100%;
    max-width: 400px;
  }
}
</style> 